import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { CoreModule } from './../core.module';
// import { NzNotificationService, NzMessageService } from 'ng-zorro-antd';
import { timeout } from 'rxjs/operators';
import { urlService } from './url';
import { Router, ActivatedRoute } from '@angular/router';
import { ToptipsService, ToptipsType } from 'ngx-weui/toptips';
import { StorageService } from '../sotrage/storage.service';
import { Location } from '@angular/common';
import { DialogConfig, DialogService } from 'ngx-weui';
import { I18nService } from '../i18n/i18n.service';

@Injectable({
	providedIn: CoreModule,
})
export class ApiService {
	msgData;
	gameToken;
	tokenUrl;
	config: DialogConfig = {
		title: '',
		content: '',
		cancel: '',
		confirm: '',
	};
	loginErrorNumConfig: DialogConfig = {
		title: '',
		content: '',
		confirm: '',
	};
	constructor(
		private i: I18nService,
		private srv: ToptipsService,
		private http: HttpClient,
		private sto: StorageService,
		private router: Router,
		private location: Location,
		private route: ActivatedRoute,
		private dialog: DialogService
	) {
		this.tokenUrl = window.location.origin + '/oauth/authorize?response_type=code&client_id=OwnUser&redirect_uri=' + window.location.origin;
		this.i.get(['loginPage.model1', 'loginPage.model2', 'loginPage.model3', 'loginPage.model4', 'AGENCY-Page.confirm']).subscribe((res) => {
			this.msgData = res;
			this.config = {
				title: res['loginPage.model1'],
				content: '',
				cancel: res['loginPage.model2'],
				confirm: res['AGENCY-Page.confirm'],
			};
			this.loginErrorNumConfig = {
				title: res['loginPage.model1'],
				content: res['loginPage.model3'],
				cancel: res['AGENCY-Page.confirm'],
				confirm: null,
			};
		});
		this.gameToken = this.sto.get('gameToken');
	}

	get(url: string, params?: { [key: string]: any }, noFail?: Boolean): Promise<Function> {
		const header = this.getHeader(url);
		const request = this.http
			.get(urlService('dev', url), {
				params,
				headers: header,
			})
			.pipe(timeout(240000))
			.toPromise();
		return new Promise((resolve, reject) => {
			request
				.then((res: any) => {
					if (res.status === '0') {
						resolve(res.data);
					} else {
						reject(res.data);
						if (!noFail) {
							this.srv.warn(res.message);
						}
					}
					if (res.status === '1326') {
						window.location.href = this.tokenUrl;
					}
				})
				.catch((res) => {
					if (res.status === 403) {
						sessionStorage.setItem('returnurl', this.router.url);
						// this.srv.warn('登录超时，请重新登录');
						window.location.href = this.tokenUrl;
					} else {
						this.srv.warn(this.msgData['loginPage.model4']);
					}
				});
		});
	}
	post(url: string, data?: { [key: string]: any }, params?: { [key: string]: any }, noFail?: Boolean, headers?: Headers, noValid?: Boolean): Promise<Function> {
		const header = this.getHeader(url);
		const request = this.http
			.post(urlService('dev', url), data, {
				params,
				headers: header,
			})
			.pipe(timeout(60000))
			.toPromise();
		return new Promise((resolve, reject) => {
			request
				.then((res: any) => {
					switch (res.status) {
						case '0':
							resolve(res);
							break;
						case '403':
							switch (url) {
								case '开始游戏':
									this.srv.warn(res.message);
									break;

								default:
									break;
							}
							// resolve(res);
							break;
						case '1332':
							res['data']['loginErrorNum'] == '3' ? this.dialog.show(this.loginErrorNumConfig).subscribe((res: any) => {}) : '';
							reject(res);
							break;
						case '1331':
							this.config.content = res.message;
							this.dialog.show(this.config).subscribe((res: any) => {
								!res.value ? this.router.navigateByUrl('/updatePwd/3') : '';
							});
							break;
						case '1326':
							window.location.href = this.tokenUrl;
							break;
						case '3003':
							this.updataToken();
							// reject(res);
							break;
						case '3002':
							window.location.href = this.tokenUrl;
							break;
						case '5206':
							if (res['data'] && res['data']['mustRecharge'] == 'Y') {
								this.post('获取相关提供商信息以及余额', { providerId: res['data'].providerId }).then((res) => {
									const data = res['data']['data'];
									if (data['balance'] == 0 && data['playerAccountType'] == 'Separate') {
										//playerAccountType : Separate独立账户才会有转移余额操作
										this.router.navigateByUrl('/wallettansfer');
									} else {
										//返回的 balance如果大于零重新调用接口 /own/startGame.do这次将会直接进入
										console.log(res);
										// this.post(url,data).then(res => {
										//     console.log(res,'++++++++')
										// })
									}
								});
							} else {
								this.srv.warn(res.message);
							}
							// resolve(res);
							break;

						default:
							if (!noFail) {
								this.srv.warn(res.message);
							}
							break;
					}
				})
				.catch((res) => {
					if (res.status === 403) {
						if (!noValid) {
							window.location.href = this.tokenUrl;
						} else {
							reject(res);
						}
					} else {
						this.srv.warn(this.msgData['loginPage.model4']);
					}
				});
		});
	}

	login(url: string, data?: string, params?: { [key: string]: any }, noFail?: Boolean, headers?: Headers, noValid?: Boolean): Promise<Function> {
		const header = this.getHeader('login');
		const request = this.http
			.post(urlService('dev', url), data, {
				params,
				headers: header,
			})
			.pipe(timeout(60000))
			.toPromise();
		return new Promise((resolve, reject) => {
			request
				.then((res: any) => {
					switch (res.status) {
						case '0':
							resolve(res);
							break;
						case '1332':
							res['data']['loginErrorNum'] == '3' ? this.dialog.show(this.loginErrorNumConfig).subscribe((res: any) => {}) : '';
							reject(res);
							break;
						case '1331':
							this.config.content = res.message;
							this.dialog.show(this.config).subscribe((res: any) => {
								!res.value ? this.router.navigateByUrl('/updatePwd/3') : '';
							});
							break;
						case '1326':
							window.location.href = this.tokenUrl;
							break;
						default:
							if (!noFail) {
								this.srv.warn(res.message);
							}
							break;
					}
				})
				.catch((res) => {
					if (res.status === 403) {
						// console.log(this.route);
						if (!noValid) {
							sessionStorage.setItem('returnurl', this.router.url);
							window.location.href = this.tokenUrl;
						} else {
							reject(res);
						}
					} else {
						this.srv.warn(this.msgData['loginPage.model4']);
					}
				});
		});
	}

	getHeader(url) {
		let l = 'zh_CN';
		let token;
		let str = '登录生成图形验证码唯一id生成图形验证码发送邮箱验证码注册设置密码(首次设置密码)';
		switch (this.sto.get('lang')) {
			case 'zh':
				l = 'zh_CN';
				break;
			case 'en':
				l = 'en_US';
				break;
			case 'jp':
				l = 'ja_JP';
				break;
		}
		const header = { lang: l };

		if (url === 'login') {
			header['Content-Type'] = 'application/x-www-form-urlencoded;';
		} else {
			this.gameToken = this.sto.get('gameToken');
			this.gameToken ? (header['Authorization'] = 'Bearer ' + this.gameToken) : null;
			// this.gameToken ? header['Authorization'] = token : '';
			// str.indexOf(url) == -1 && this.gameToken ? header['Authorization'] = token : null;
		}

		return header;
	}

	msgSuccess(t) {
		this.srv.success(t);
	}

	msgEeeor(t) {
		this.srv.warn(t);
	}

	updataToken() {
		let user = this.sto.get('user');
		let gameToken = JSON.parse(user['token']);
		this.post('刷新令牌', { refreshToken: gameToken['refresh_token'] })
			.then((res) => {
				this.gameToken = JSON.parse(res['data']);
				this.sto.set('token', this.gameToken);
				this.sto.set('gameToken', this.gameToken['access_token']);
			})
			.catch((res) => {
				console.log(res, '333');
			});
	}
}
